package com.softserveinc.fragments.adapter;

import java.util.ArrayList;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.softserveinc.data.help.MovieListType;
import com.softserveinc.fragments.MovieListFragment;
import com.viewpagerindicator.TitleProvider;

public class MovieFragmentAdapter extends FragmentPagerAdapter implements
		TitleProvider {

	protected static final String TAG = MovieFragmentAdapter.class
			.getSimpleName();

	private MovieListFragment ratingList = new MovieListFragment(
			MovieListType.RATING);
	private MovieListFragment releaseDateList = new MovieListFragment(
			MovieListType.RELEASE_DATE);
	private MovieListFragment titleList = new MovieListFragment(
			MovieListType.TITLE);

	private final String[] titles = new String[] { "Most popular", "Recent",
			"By title" };

	@SuppressWarnings("serial")
	private final ArrayList<MovieListFragment> movieListFragments = new ArrayList<MovieListFragment>() {
		{
			add(ratingList);
			add(releaseDateList);
			add(titleList);
		}
	};

	public MovieFragmentAdapter(final FragmentManager fm,
			final int firstVisiblePosition) {
		super(fm);

		movieListFragments.get(firstVisiblePosition).setRunWithData(true);
	}

	@Override
	public Fragment getItem(final int position) {
		return movieListFragments.get(position);
	}

	@Override
	public int getCount() {
		return movieListFragments.size();
	}

	@Override
	public String getTitle(final int position) {
		return titles[position];
	}

	public void updateData(final int position, final int previousPosition) {
		MovieListFragment fragment = movieListFragments.get(position);

		fragment.displayPosters();

		if (previousPosition >= 0 && previousPosition != position) {
			fragment = movieListFragments.get(previousPosition);
			fragment.recyclePosters();
		}
	}
}
